package com.hepinghospital.user.ui.activity.prescription;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hepinghospital.user.R;
import com.hepinghospital.user.base.BaseActivity;
import com.hepinghospital.user.base.BaseApplication;
import com.hepinghospital.user.ui.dialog.ApplyQuitDialog;
import com.hepinghospital.user.util.ImageLoaderHelper;
import com.hepinghospital.user.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.observer.BaseObserver;
import com.rest.response.MedicineListResponse;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.UtilList;
import jz.joyoung.robot.util.UtilString;

/**
 * 我的药品 -> 处方订单
 * Created by lbj on 2021/8/18 16:59
 */
public class MyMedicineActivity extends BaseActivity {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.cl_empty)
    ConstraintLayout clEmpty;

    int current = 1;
    List<MedicineListResponse.MedicineOrder> mList = new ArrayList<>();
    MyAdapter adapter;

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_base_list;
    }

    @Override
    protected void initViews() {
        tvTitle.setText("药品订单");
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        adapter = new MyAdapter();
        recyclerView.setAdapter(adapter);
        refreshLayout.setOnRefreshListener(refreshlayout -> {
            current = 1;
            getMedicineOrderList();
        });

        //加载更多
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            current++;
            getMedicineOrderList();
        });
    }

    @Override
    protected void initData() {

    }


    @Override
    protected void onResume() {
        super.onResume();
        getMedicineOrderList();
    }

    private void getMedicineOrderList() {
        RestProxy.getInstance().getMedicineOrderList(BaseApplication.currentUserId, current + "", new BaseObserver<MedicineListResponse>() {

            @Override
            public void onSuccess(MedicineListResponse medicineListResponse) {
                List<MedicineListResponse.MedicineOrder> list = medicineListResponse.records;
                if (current == 1) {
                    if (!UtilList.isEmpty(list)) {
                        refreshLayout.setVisibility(View.VISIBLE);
                        clEmpty.setVisibility(View.GONE);
                        mList.clear();
                        mList.addAll(list);
                        adapter.notifyDataSetChanged();
                        refreshLayout.finishRefresh(true);
                    } else {
                        refreshLayout.setVisibility(View.GONE);
                        clEmpty.setVisibility(View.VISIBLE);
                    }
                } else {
                    mList.addAll(list);
                    adapter.notifyDataSetChanged();
                    refreshLayout.finishLoadMore(true);
                    if (list.size() < 10) {
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
                if (current == 1) {
                    refreshLayout.finishRefresh(false);
                } else {
                    refreshLayout.finishLoadMore(false);
                }
            }
        });
    }

    class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {


        @NotNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            Context context = parent.getContext();
            View view = LayoutInflater.from(context)
                    .inflate(R.layout.item_my_medicine, parent, false);
            return new ViewHolder(view);

        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
            final ViewHolder mHolder = (ViewHolder) holder;
            int orderStatus = mList.get(position).orderStatus;
            String status = mList.get(position).status;
            String receiveType = mList.get(position).receiveType;
            holder.itemView.setOnClickListener(v -> {
                if ("1".equals(status)) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("obj", mList.get(position));
                    startActivity(MedicineDetailActivity.class, bundle);
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString("orderId", mList.get(holder.getAdapterPosition()).orderId);
                    startActivity(AtyOrderMedicineDetailActivity.class, bundle);
                }

            });
            mHolder.tvDepartment.setText(mList.get(position).deptName);
            setStatusColor(mHolder.tvStatus, status);
//            mHolder.tvStatus.setText( getStatus( mList.get( position ).status ) );
            mHolder.tvStatus.setText(mList.get(position).statusName);
            mHolder.tvDrugname.setText(mList.get(position).prescriptionList);
            mHolder.tvPrice.setText("¥" + mList.get(position).prescriptionAmount);
            if (!TextUtils.isEmpty(mList.get(position).expressNum)) {
                mHolder.tvExpress.setText(mList.get(position).express + ":" + mList.get(position).expressNum);
            }
            mHolder.tvName.setText(mList.get(position).doctorName);
            if ("1".equals(status)) {
                final int parseInt = Integer.parseInt(mList.get(position).remainPayTime);
                if (parseInt > 0) {
                    mHolder.llPayTime.setVisibility(View.VISIBLE);
                    mHolder.tvExpress.setVisibility(View.GONE);
                    if (mHolder.timer != null) {
                        mHolder.timer.cancel();
                    }
                    mHolder.timer = new CountDownTimer(parseInt * 1000, 1000) {
                        @Override
                        public void onTick(long millisUntilFinished) {

                            mHolder.tvDetail.setText(millisUntilFinished / 60000 / 60 + "时" + millisUntilFinished / 60000 % 60 + "分" + (millisUntilFinished / 1000) % 60 + "秒");
//                        holder.tv_detail.setText("请在" + Integer.parseInt(list.get(position).remainPayTime  )/60 + "分"+Integer.parseInt(list.get(position).remainPayTime  )%60 + "秒" + "之内完成支付");
                        }

                        @Override
                        public void onFinish() {//倒计时为0时执行此方法
                            mHolder.timer.cancel();
                            mHolder.llPayTime.setVisibility(View.GONE);
                            mHolder.tvExpress.setVisibility(View.VISIBLE);
                            mHolder.tvExpress.setText("已超时");

                        }
                    };
                    mHolder.timer.start();
                } else {
                    mHolder.llPayTime.setVisibility(View.GONE);
                    mHolder.tvExpress.setVisibility(View.VISIBLE);
                    mHolder.tvExpress.setText("已超时");
                }

            } else {
                mHolder.llPayTime.setVisibility(View.GONE);
                mHolder.tvExpress.setVisibility(View.VISIBLE);
                if ("1".equals(receiveType)) {
                    mHolder.tvExpress.setText("配药方式：物流配送");
                } else {
                    mHolder.tvExpress.setText("配药方式：到院自取");
                }
            }
            if ("4".equals(status)) {
                mHolder.tvLookWuliu.setVisibility(View.VISIBLE);
            } else {
                mHolder.tvLookWuliu.setVisibility(View.GONE);
            }
//            if ("5".equals(status) || "7".equals(status)) {//已完成，已取消
//                mHolder.lineTwo.setVisibility(View.GONE);
//            } else {
//                mHolder.lineTwo.setVisibility(View.VISIBLE);
//            }

            switch (status) {
                case "1":
                    mHolder.tvPay.setVisibility(View.VISIBLE);
                    mHolder.tvCancel.setVisibility(View.VISIBLE);
                    mHolder.tvCancel.setText("取消订单");
                    mHolder.tvPay.setText("立即支付");
                    break;
                case "3": //待发货，申请退药
                case "6": //到院自取,待取药
                    mHolder.tvPay.setVisibility(View.GONE);
                    mHolder.tvCancel.setVisibility(View.VISIBLE);
                    mHolder.tvCancel.setText("申请退药");
                    break;
                case "4": //已发货 代签收
                    mHolder.tvPay.setVisibility(View.VISIBLE);
                    mHolder.tvCancel.setVisibility(View.VISIBLE);
                    mHolder.tvCancel.setText("申请退药");
                    mHolder.tvPay.setText("确认收货");
                    break;
                case "5": //已完成
                    if ("1".equals(receiveType)) {
                        mHolder.tvPay.setVisibility(View.GONE);
                        mHolder.tvCancel.setVisibility(View.VISIBLE);
                        mHolder.tvCancel.setText("申请退药");
                    } else {
                        mHolder.tvPay.setVisibility(View.GONE);
                        mHolder.tvCancel.setVisibility(View.GONE);
                    }

                    break;
                //已取消,取消订单,11已经退药
                case "103": //申请退药(当前待发货)
                case "104":
                case "105": //申请退药(当前待签收)，105代表收货之后申请退药
                    mHolder.tvPay.setVisibility(View.VISIBLE);
                    mHolder.tvCancel.setVisibility(View.GONE);
                    mHolder.tvPay.setText("取消退药");
                    break;
                case "204":
                case "205": //同意退药，等待寄回(未收货)
                    mHolder.tvPay.setVisibility(View.VISIBLE);
                    mHolder.tvCancel.setVisibility(View.VISIBLE);
                    mHolder.tvCancel.setText("取消退药");
                    mHolder.tvPay.setText("录入快递单");
                    break;
                default:
                    mHolder.tvPay.setVisibility(View.GONE);
                    mHolder.tvCancel.setVisibility(View.GONE);
                    break;
            }


            mHolder.tvCancel.setOnClickListener(v -> {
                switch (status) {
                    case "1":  //取消订单
                        updatePrescriptionStatus(mList.get(position).prescriptionId, "7");
                        break;
                    case "3":
                    case "4":
                    case "5":
                    case "6": //待发货,已发货,
                        showApplyQuitDialog(position, "8");
                        break;
                    case "204": //取消退药
                    case "205":
                        showApplyQuitDialog(position, "12");
                        break;
                    default:
                        //cancelOrder( mList.get( position ).orderId );
                        break;
                }
            });
            mHolder.tvPay.setOnClickListener(v -> {
                switch (status) {
                    case "1":  //待支付
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("obj", mList.get(position));
                        startActivity(MedicineDetailActivity.class, bundle);
                        break;
                    case "4": //确认收货
                        updatePrescriptionStatus(mList.get(position).prescriptionId, "5");
                        break;
                    case "103":
                    case "104":
                    case "105": //取消退药
                        showApplyQuitDialog(position, "12");
                        break;
                    case "204":
                    case "205": //录入快递单
                        startActivity(new Intent(mContext, AddExpressActivity.class).putExtra("prescriptionId", mList.get(position).prescriptionId).putExtra("status", status));
                        break;
                    default:
                        cancelOrder(mList.get(position).orderId);
                        break;
                }
            });
            mHolder.tvLookWuliu.setOnClickListener(v -> {
//                String waybillNo = mList.get(position).waybillNo;
//                String logistics = mList.get(position).logistics;
                String prescriptionId = mList.get(position).prescriptionId;
                if (!UtilString.isEmpty(prescriptionId)) {
                    startActivity(new Intent(mContext, AtyLogisticsActivity.class).putExtra("prescriptionId", prescriptionId));
                } else {
                    ToastUtil.showToastCenter(mContext, "运单号为空");
                }
            });

            if (orderStatus == 401) {//将前一个缓存清除 ,待支付


            }

            ImageLoaderHelper.getInstance().GlideCircleImageLoader(mContext, mList.get(position).url, mHolder.imgHead);
        }

        @Override
        public int getItemCount() {
            return mList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {

            @BindView(R.id.img_head)
            ImageView imgHead;
            @BindView(R.id.tv_name)
            TextView tvName;
            @BindView(R.id.tv_department)
            TextView tvDepartment;
            @BindView(R.id.tv_status)
            TextView tvStatus;
            @BindView(R.id.tv_drugname)
            TextView tvDrugname;
            @BindView(R.id.tv_price)
            TextView tvPrice;
            @BindView(R.id.tv_express)
            TextView tvExpress;
            @BindView(R.id.tv_detail)
            TextView tvDetail;
            @BindView(R.id.ll_pay_time)
            LinearLayout llPayTime;
            @BindView(R.id.tv_cancel)
            TextView tvCancel;
            @BindView(R.id.tv_look_wuliu)
            TextView tvLookWuliu;
            @BindView(R.id.tv_pay)
            TextView tvPay;
//            @BindView(R.id.line_two)
//            View lineTwo;

            private CountDownTimer timer;

            ViewHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }
        }
    }

    private void cancelOrder(String orderId) {
        RestProxy.getInstance().cancelOrder(orderId, new BaseObserver<String>() {
            @Override
            public void onSuccess(String s) {
                getMedicineOrderList();
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }

        });
    }

    private void setStatusColor(TextView tvStatus, String status) {
        switch (status) {
            case "5":
            case "7":
            case "11":
                tvStatus.setTextColor(ContextCompat.getColor(mContext, R.color.ff999999));
                break;

            default:
                tvStatus.setTextColor(ContextCompat.getColor(mContext, R.color.fff54c4c));
        }
    }

    private String getStatus(String status) {
        switch (status) {
            case "1":
                return "待支付";
            case "2":
                return "驳回";
            case "3":
                return "待发货";
            case "4": //待签收
                return "已收货";
            case "5":
                return "已完成";
            case "6":
                return "待取药";
            case "7":
                return "已取消";
            case "8":
                return "申请退药";
            case "9":
                return "同意退药，等待寄回";
            case "10":
                return "药品寄回中";
            case "11":
                return "已退药";
            case "12":
                return "取消退药";
            default:
                return "";
        }
    }


    private void updatePrescriptionStatus(String prescriptionId, String status) {
        showLoadingDialog(mContext);
        Map<String, Object> map = new HashMap<>();
        map.put("id", prescriptionId);
        map.put("status", status);
        RestProxy.getInstance().updatePrescriptionStatus(map, new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Boolean s) {
                dismissLoadingDialog();
                if(s) {
                    getMedicineOrderList();
                }
            }

            @Override
            public void onError(Throwable e) {
                dismissLoadingDialog();
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {
                dismissLoadingDialog();
            }
        });
    }

    private void showApplyQuitDialog(int position, String status) {
        ApplyQuitDialog applyQuitDialog = ApplyQuitDialog.newInstance(status, true);//申请退药
        applyQuitDialog.show(getSupportFragmentManager(), "applyQuitDialog");
        applyQuitDialog.setmListener(new ApplyQuitDialog.OnItemClickListener() {

            @Override
            public void onConfirm() {
                updatePrescriptionStatus(mList.get(position).prescriptionId, status);
            }

            @Override
            public void onCancel() {

            }
        });
    }
}
